package com.axend.aerosense.room.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.IComplete;
import com.axend.aerosense.base.impl.IOperationDetailResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.common.bean.UserIconBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.util.HeadIconUploadService;
import com.axend.aerosense.common.util.UserImageEngine;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.room.entity.Height;
import com.axend.aerosense.room.entity.PersonInfoBean;
import com.axend.aerosense.room.entity.PhoneAreaCodeBean;
import com.axend.aerosense.room.ui.activity.PeoplePickerActivity;
import com.axend.aerosense.room.ui.activity.PhoneCodePieckerActivity;
import com.axend.aerosense.room.viewmodel.WardInfoViewModel;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.ui.BottomTextPickerDialog;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.room.BR;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomFragmentNewWardBinding;
import com.axend.aerosense.room.entity.WardInfoBean;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.util.List;


/**
 * 受监护人新增界面
 */
public class RoomWardSettingFragment extends MvvmBaseFragment<RoomFragmentNewWardBinding, WardInfoViewModel>
        implements ILoadDataResult<WardInfoBean>, IOperationResult, IComplete {
    public static final int REQUEST_TYPE = 14;
    public final static String OPEN_UID = "OPEN_UID";
    // 查看/编辑的 人物的id
    private String uid = null;
    private CustomTipsDialog dialog = null;
    // 是否是创建模式R
    private boolean CREATE_OPEN_MODE = false;
    String[] stringArrary;
    private Bitmap upBitmap;


    @Override
    protected void initParameters() {
        super.initParameters();
        Bundle bundle = getArguments();
        if(null != bundle) {
            uid = bundle.getString(OPEN_UID);
        }
        if(TextUtils.isEmpty(uid)){
            CREATE_OPEN_MODE = true;
        }else{
            CREATE_OPEN_MODE = false;
        }

        stringArrary = getResources().getStringArray(R.array.common_sex_list);
    }

    public static RoomWardSettingFragment getInstance(String uid){
        RoomWardSettingFragment fragment = new RoomWardSettingFragment();
        if(!TextUtils.isEmpty(uid)){
            Bundle bundle = new Bundle();
            bundle.putString(OPEN_UID, uid);
            fragment.setArguments(bundle);   //设置参数
        }
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_fragment_new_ward;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected WardInfoViewModel getViewModel() {
        BaseViewModelFactroy<WardInfoBean> factroy = new BaseViewModelFactroy<WardInfoBean>(this, this);
        WardInfoViewModel tmp = new ViewModelProvider(this, factroy).get(WardInfoViewModel.class);
        if(CREATE_OPEN_MODE){
            // 创建模式, 默认可编辑
            tmp.edit.setValue(true);
            tmp.editHeadImage.setValue(false);
        }else{
            // 已有模式打开,默认不能编辑
            tmp.edit.setValue(false);
            tmp.editHeadImage.setValue(true);
        }
        tmp.setOnOpresionListence(this);
        return tmp;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    public void onResume() {
        super.onResume();
        ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
        if(CREATE_OPEN_MODE){
            // 此处是创建模式
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.room_add_warder));
            ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_complete));

        }else{
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.common_detail));
            if(viewModel.edit.getValue()){
                ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_save));
            }else{
                ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_edit));
            }
        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init(){
        if(!CREATE_OPEN_MODE){
            setLoadSir(viewDataBinding.roomContentView);
            showLoading();
            viewModel.getWard(getActivity(), uid);
        }

        viewDataBinding.roomPhoneCode.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), PhoneCodePieckerActivity.class);
            getActivity().startActivityForResult(intent, PhoneCodePieckerActivity.WARD_REQUEST_CODE);
        });

        //生日
        viewDataBinding.roomPersonDataRightLayout.setOnClickListener(v->{
            long minMillseconds = -5364635954L; // 默认最小年份1800年
            long Years_400 = 400L * 365 * 1000 * 60 * 60 * 24L;  // 范围为400年
            BottomTimeDialogFragment fragment = new BottomTimeDialogFragment.Builder()
                    .setType(Type.YEAR_MONTH_DAY)
                    .setMaxMillseconds(minMillseconds + Years_400)
                    .setCurrentMillseconds(-315592754) // 默认1960年
                    .setWheelItemTextSize(16)
                    .setThemeColor(getResources().getColor(R.color.app_colorAccent, null))
                    .setCallBack((OnDateSetListener<String>) (timePickerView, date) -> {
                        WardInfoBean bean = viewModel.wardInfo.getValue();
                        bean.setWardBirthday(date);
                        viewModel.wardInfo.postValue(bean);
                    })
                    .build();
            fragment.show(getChildFragmentManager(), BottomTimeDialogFragment.class.getSimpleName());
        });
        viewDataBinding.roomPersonDataTv.setOnClickListener(v -> {
            viewDataBinding.roomPersonDataRightLayout.performClick();
        });

        //体重
        viewDataBinding.roomWeightRightLayout.setOnClickListener(v->{
            BottomNumberPickerDialog fragment = new BottomNumberPickerDialog.Builder()
                    .setType(Type.NUMBER)
                    .setMinValue(10)
                    .setMaxValue(120) // 最大120kg
                    .setDefValue(50)  // 默认50kg
                    .setUnit("kg")
                    .setWheelItemTextSize(16)
                    .setThemeColor(getResources().getColor(R.color.app_colorAccent, null))
                    .setCallBack((OnDateSetListener<Integer>) (timePickerView, weight) -> {
                        WardInfoBean bean = viewModel.wardInfo.getValue();
                        bean.setWardWeight(weight);
                        viewModel.wardInfo.postValue(bean);
                    })
                    .build();
            fragment.show(getChildFragmentManager(), BottomNumberPickerDialog.class.getSimpleName());
        });
        viewDataBinding.roomPersonWeightTv.setOnClickListener(v -> {
            viewDataBinding.roomWeightRightLayout.performClick();
        });

        //身高
        viewDataBinding.roomHightRightLayout.setOnClickListener(v->{
            BottomNumberPickerDialog fragment = new BottomNumberPickerDialog.Builder()
                    .setType(Type.NUMBER)
                    .setMinValue(0)
                    .setMaxValue(210) // 最大120kg
                    .setDefValue(175)  // 默认50kg
                    .setUnit("cm")
                    .setWheelItemTextSize(16)
                    .setThemeColor(getResources().getColor(R.color.app_colorAccent, null))
                    .setCallBack((OnDateSetListener<Integer>) (timePickerView, height) -> {
                        WardInfoBean bean = viewModel.wardInfo.getValue();
                        bean.setWardHeight(String.valueOf(height));
                        viewModel.wardInfo.postValue(bean);
                    })
                    .build();
            fragment.show(getChildFragmentManager(), BottomNumberPickerDialog.class.getSimpleName());

//            BottomHeightPickerDialog fragment = new BottomHeightPickerDialog.Builder()
//                    .setType(Type.NUMBER, Type.NUMBER)
//                    .setMinValue(3, 0) //最小120 公分
//                    .setMaxValue(6, 9) // 最高250公分
//                    .setDefValue(4, 5) //默认160公分
//                    .setUnit("ft", "in")
//                    .setWheelItemTextSize(16, 16)
//                    .setThemeColor(getResources().getColor(R.color.app_colorAccent, null))
//                    .setCallBack((OnDateSetListener<Height>) (tmp, hight) -> {
//                        WardInfoBean bean = viewModel.wardInfo.getValue();
//                        bean.setWardHeight(hight.toSeverString());
//                        viewModel.wardInfo.postValue(bean);
//                    })
//                    .build();
//            fragment.show(getChildFragmentManager(), BottomHeightPickerDialog.class.getSimpleName());
        });
        viewDataBinding.roomPersonHightTv.setOnClickListener(v -> {
            viewDataBinding.roomHightRightLayout.performClick();
        });

        //性别
        viewDataBinding.roomSexRightLayout.setOnClickListener(v->{
            BottomTextPickerDialog fragment = new BottomTextPickerDialog.Builder()
                    .setType(Type.NUMBER)
                    .setWheelItemTextSize(16)
                    .setThemeColor(getResources().getColor(R.color.app_colorAccent, null))
                    .setIndexCallBack((timePickerView, index) -> {
                        WardInfoBean bean = viewModel.wardInfo.getValue();
                        bean.setWardSexType(index);
                        viewDataBinding.roomPersonSex.setText(stringArrary[index]);
                        viewModel.wardInfo.postValue(bean);
                    })
                    .build(stringArrary);
            fragment.show(getChildFragmentManager(), BottomTextPickerDialog.class.getSimpleName());
        });
        viewDataBinding.roomPersonSexTv.setOnClickListener(v -> {
            viewDataBinding.roomSexRightLayout.performClick();
        });

        if(!CREATE_OPEN_MODE){
            viewDataBinding.roomDelete.setVisibility(View.VISIBLE);
            viewDataBinding.roomDelete.setOnClickListener(v -> {
                dialog = new CustomTipsDialog(getActivity(), getActivity().getString(R.string.common_delete_ward));
                dialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener(){

                    @Override
                    public void onPositiveClick() {
                        dialog.dismiss();
                        viewModel.onDeletWard(getActivity(), uid);
                    }

                    @Override
                    public void onNegtiveClick() {
                        dialog.dismiss();
                    }
                });
                dialog.show();

            });
        }else{
            // 创建模式打开
            viewDataBinding.roomDelete.setVisibility(View.GONE);
        }

        viewDataBinding.roomUserHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View inflate = LayoutInflater.from(getContext()).inflate(R.layout.common_head_popup_window, null);
                TextView tvPhoto = inflate.findViewById(R.id.common_tv_photo);  //调用照相机
                TextView tvAlbum = inflate.findViewById(R.id.common_tv_album);  //调用相册
                TextView tvCancel = inflate.findViewById(R.id.common_tv_cancel);

                final PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
                popupWindow.setOutsideTouchable(true);//设置外部可触摸
                popupWindow.setFocusable(true);//这里必须设置为true才能点击区域外或者消失
                popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                //得到父layout
                View parent = LayoutInflater.from(getActivity()).inflate(getLayoutId(), null);
                //展示在parent的下方，0,0的位置
                popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);

                //popupWindow在弹窗的时候背景半透明
                final WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();

                params.alpha = 0.5f;
                getActivity().getWindow().setAttributes(params);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        params.alpha = 1.0f;
                        getActivity().getWindow().setAttributes(params);
                    }
                });
                //拍照选择
                tvPhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loadPicture(RoomWardSettingFragment.this);
                        popupWindow.dismiss();
                    }
                });
                //从相册中选择
                tvAlbum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loadPicture(RoomWardSettingFragment.this);
                        popupWindow.dismiss();
                    }
                });
                //关闭弹出
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

            }
        });

    }

    @Override
    public void complete() {
        long currentTime = System.currentTimeMillis();
        if(currentTime - clickTime < 2*1000){
            return;
        }
        clickTime = currentTime;
        if(!CREATE_OPEN_MODE){
            if(viewModel.edit.getValue()){
                // 检查数据是否有更新,有更新数据
                viewModel.updateWard(getActivity(), uid, new IOperationResult() {
                    @Override
                    public void onSuccess() {
                        if(null == upBitmap){
                            ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_edit));
                            ToastUtils.showShort(getActivity().getText(R.string.common_success));
                            viewModel.edit.setValue(false);
                            getActivity().onBackPressed();
                            return;
                        }
                        HeadIconUploadService.upload(upBitmap, 2, uid, new SimpleCallBack<UserIconBean>() {
                            @Override
                            public void onError(ApiException e) {
                                e.printStackTrace();
                                ToastUtils.showShort(e.getMessage());
                                ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_save));
                                viewModel.edit.setValue(true);
                            }

                            @Override
                            public void onSuccess(UserIconBean bean) {
                                // 可编辑模式下,可编辑状态点击工具栏,应当关闭编辑,提示变为编辑
                                ToastUtils.showShort(getResources().getText(R.string.common_success));
                                ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_edit));
                                viewModel.edit.setValue(false);
                                upBitmap = null;
                                getActivity().onBackPressed();

                            }

                            @Override
                            public void onTokenExpire() {
                                upBitmap = null;
                                ToastUtils.showShort(R.string.common_login_first);
                                ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                            }
                        });

                    }

                    @Override
                    public void onFail() {
                        // 可编辑模式下,不可编辑状态点击工具栏,应当打开编辑,提示变为保存
                        ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_save));
                        viewModel.edit.setValue(true);
                    }
                });
            }else{
                // 可编辑模式下,不可编辑状态点击工具栏,应当打开编辑,提示变为保存
                ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_save));
                viewModel.edit.setValue(true);
            }
        }else{
            // 此处提交创建数据
            viewModel.onAddWard(getActivity(), upBitmap, new IOperationDetailResult<WardInfoBean>() {
                @Override
                public void onSuccess(WardInfoBean bean) {
                    if(upBitmap == null){
                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.WARD_COUNT_CHANGE ,Integer.class).postValue(1);
                        getActivity().onBackPressed();

                    }else{
                        upBitmap = null;
                        //此处目前是为一个废对象不做处理的
                        ToastUtils.showShort(Utils.getApp().getString(R.string.common_success));
                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.WARD_COUNT_CHANGE ,Integer.class).postValue(1);
                        getActivity().onBackPressed();
                    }
                }

                @Override
                public void onFail(int errCode, String message) {

                }
            });
        }

    }

    @Override
    public void loadDataSuccess(WardInfoBean wardInfoBean) {
        ((PeoplePickerActivity)getActivity()).setTitle(wardInfoBean.getWardName());
        Glide.with(getActivity()).load(wardInfoBean.getWardImg()).placeholder(R.mipmap.common_img_default_head)
                .skipMemoryCache(true)
                .diskCacheStrategy( DiskCacheStrategy.NONE ).circleCrop().into(viewDataBinding.roomUserHead);
        viewDataBinding.roomPersonSex.setText(stringArrary[wardInfoBean.getWardSexType()]);
        viewModel.setValue(wardInfoBean);
    }

    @Override
    public void loadDataFail(String decs) {
        ToastUtils.showShort(decs);
    }

    @Override
    public void onSuccess() {
        getActivity().onBackPressed();
    }

    @Override
    public void onFail() {

    }

    public void setPhoneCode(PhoneAreaCodeBean bean){
        if(null == bean){
            return;
        }
        WardInfoBean personInfoBean = viewModel.wardInfo.getValue();
        personInfoBean.setWardPhoneAreaCode(bean.getAreaCodePhone());
        viewModel.wardInfo.postValue(personInfoBean);
    }

    private void loadPicture(Fragment fragment){
        PictureSelector.create(fragment)
                .openGallery(PictureMimeType.ofImage())  //打开相册
                .imageEngine(UserImageEngine.createGlideEngine())
                .selectionMode(PictureConfig.SINGLE) //单选模式
                .isEnableCrop(true) //可以裁剪
//                                .circleDimmedLayer(true) //圆形裁剪框
//                                .setCircleStrokeWidth(3) //圆形裁剪框宽度
                .showCropFrame(true) //不显示矩形裁剪框
                .hideBottomControls(true) //隐藏裁剪工具栏
                .isCompress(true) //压缩图片
                .minimumCompressSize(10) //大于100kb都要压缩
                .withAspectRatio(1, 1)//裁剪比例
                .cropImageWideHigh(170, 170)//裁剪宽高
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        LocalMedia localMedia = result.get(0);
                        String path = "";
                        if (localMedia.isCut()) {//是否裁剪
                            path = localMedia.getCutPath();
                        } else {
                            path = localMedia.getRealPath();
                        }
                        Glide.with(fragment).asBitmap().load(path).into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                upBitmap = resource;
                                Glide.with(fragment).load(resource).circleCrop().into(viewDataBinding.roomUserHead);
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                    }
                });
    }
}
